package com.itheima.service.db.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.util.ComputeUtil;
import com.itheima.vo.AnalysisSummaryVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    @Override
    public void analysis() {
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();

        //1. 从log表中进行查询
        Integer numRegistered = logMapper.countByTypeAndTime("0102", today);//新注册用户数
        Integer numActive = logMapper.countByTime(today);//活跃用户数
        Integer numLogin = logMapper.countByTypeAndTime("0101", today);//登录次数
        Integer numRetention1d = logMapper.keep(yesterday, today);//次日留存用户数

        //2. 向tb_analysis_by_day保存数据
        //2-1 先根据今天日期查询一下是否存在了记录
        QueryWrapper<AnalysisByDay> wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(wrapper);

        if (analysisByDay == null) {
            //2-2 如果没有,新增
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);

            analysisByDayMapper.insert(analysisByDay);
        } else {
            //2-3 如果有了,修改
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);

            analysisByDayMapper.updateById(analysisByDay);
        }
    }


    //概要统计
    @Override
    public AnalysisSummaryVo summary() {
        System.out.println("123123123123132132233213");
        //1. 准备基础数据
        //1-1 定义日期
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();
        String today_7 = DateUtil.offsetDay(new Date(), -7).toDateStr();
        String today_30 = DateUtil.offsetDay(new Date(), -30).toDateStr();

        //1-2 查询今天的数据
        QueryWrapper<AnalysisByDay> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("record_date", today);
        AnalysisByDay todayData = analysisByDayMapper.selectOne(wrapper1);

        //1-3 查询昨天天的数据
        QueryWrapper<AnalysisByDay> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("record_date", yesterday);
        AnalysisByDay yesterdayData = analysisByDayMapper.selectOne(wrapper2);


        //2. 凑齐9个数
        //累计用户数(分析表中sum(num_registered))
        Long cumulativeUsers = analysisByDayMapper.findRegisterNum();

        //过去30天活跃用户数(30-今天之内的活跃用户数加和)
        Long activePassMonth = analysisByDayMapper.findActiveNum(today_30, today);

        //过去7天活跃用户
        Long activePassWeek = analysisByDayMapper.findActiveNum(today_7, today);


        //今日新增用户数量
        Long newUsersToday = todayData.getNumRegistered().longValue();

        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌   BigDecimal : 商业数字格式
        BigDecimal newUsersTodayRate = ComputeUtil.computeRate(todayData.getNumRegistered(), yesterdayData.getNumRegistered());

        //今日登录次数
        Long loginTimesToday = todayData.getNumLogin().longValue();

        //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal loginTimesTodayRate = ComputeUtil.computeRate(todayData.getNumLogin(), yesterdayData.getNumLogin());

        //今日活跃用户数量
        Long activeUsersToday = todayData.getNumActive().longValue();

        //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal activeUsersTodayRate = ComputeUtil.computeRate(todayData.getNumActive(), yesterdayData.getNumActive());

        //3. 组装vo
        AnalysisSummaryVo analysisSummaryVo = new AnalysisSummaryVo();
        analysisSummaryVo.setCumulativeUsers(cumulativeUsers);
        analysisSummaryVo.setActivePassMonth(activePassMonth);
        analysisSummaryVo.setActivePassWeek(activePassWeek);
        analysisSummaryVo.setNewUsersToday(newUsersToday);
        analysisSummaryVo.setNewUsersTodayRate(newUsersTodayRate);
        analysisSummaryVo.setLoginTimesToday(loginTimesToday);
        analysisSummaryVo.setLoginTimesTodayRate(loginTimesTodayRate);
        analysisSummaryVo.setActiveUsersToday(activeUsersToday);
        analysisSummaryVo.setActiveUsersTodayRate(activeUsersTodayRate);

        return analysisSummaryVo;
    }

    //新增、活跃用户、次日留存率
    @Override
    public Map<String, List> countDashboard(String type, String beginTime, String overTime, String lastBeginTime, String lastOverTime) {

        System.out.println("1=========================================================");
        //查询开始时间到结束时间的数据集合
        List<AnalysisByDay> list = analysisByDayMapper.findNewUser(beginTime, overTime);


        //查询从去年开始时间到去年结束时间的数据集合
        List<AnalysisByDay> lastList = analysisByDayMapper.findNewUser(lastBeginTime, lastOverTime);

        System.out.println("2=========================================================");

        Map<String, List> map = new HashMap<>();
        List listBack = new ArrayList<>();
        List lastBackList = new ArrayList<>();

        //查询新增
        if (type.equals("101")) {
            //封装新增数据
            for (AnalysisByDay analysisByDay : list) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String recordDate = sdf.format(analysisByDay.getRecordDate());
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("title", recordDate);
                hashMap.put("amount", analysisByDay.getNumRegistered());
                /*AnalysisDashboardVo analysisDashboardVo = new AnalysisDashboardVo();
                analysisDashboardVo.setTitle(recordDate);
                analysisDashboardVo.setAmount(analysisByDay.getNumRegistered());*/
                listBack.add(hashMap);
            }
            map.put("thisYear", listBack);
            for (AnalysisByDay analysisByDay : lastList) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String recordDate = sdf.format(analysisByDay.getRecordDate());
                HashMap<String, Object> hashMap1 = new HashMap<>();
                hashMap1.put("title", recordDate);
                hashMap1.put("amount", analysisByDay.getNumRegistered());
                lastBackList.add(hashMap1);
            }
            map.put("lastYear", lastBackList);
            return map;

            //查询活跃
        } else if (type.equals("102")) {
            for (AnalysisByDay analysisByDay : list) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String recordDate = sdf.format(analysisByDay.getRecordDate());
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("title", recordDate);
                hashMap.put("amount", analysisByDay.getNumActive());
                /*AnalysisDashboardVo analysisDashboardVo = new AnalysisDashboardVo();
                analysisDashboardVo.setTitle(recordDate);
                analysisDashboardVo.setAmount(analysisByDay.getNumActive());*/
                listBack.add(hashMap);
            }
            map.put("thisYear", listBack);
            for (AnalysisByDay analysisByDay : lastList) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String recordDate = sdf.format(analysisByDay.getRecordDate());
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("title", recordDate);
                hashMap.put("amount", analysisByDay.getNumActive());
                lastBackList.add(hashMap);
            }
            map.put("lastYear", lastBackList);
            return map;

            //查询次日留存
        } else {
            for (AnalysisByDay analysisByDay : list) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String recordDate = sdf.format(analysisByDay.getRecordDate());
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("title", recordDate);
                hashMap.put("amount", analysisByDay.getNumRetention1d());
                /*AnalysisDashboardVo analysisDashboardVo = new AnalysisDashboardVo();
                analysisDashboardVo.setTitle(recordDate);
                analysisDashboardVo.setAmount(analysisByDay.getNumRetention1d());*/
                listBack.add(hashMap);
            }
            map.put("thisYear", listBack);
            for (AnalysisByDay analysisByDay : lastList) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String recordDate = sdf.format(analysisByDay.getRecordDate());
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("title", recordDate);
                hashMap.put("amount", analysisByDay.getNumRetention1d());
                lastBackList.add(hashMap);
            }
            map.put("lastYear", lastBackList);
            return map;
        }
    }
}